﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YXShop.IDAL.SystemInfo;
using System.Collections;

namespace YXShop.SQLServerDAL.SystemInfo
{
    public class UpgradeDataBase : IUpgradeDataBase
    {
        /// <summary>
        /// 通过版本号去判断更新数据库
        /// </summary>
        /// <param name="sqlText"></param>
        /// <returns></returns>
        public bool UpdateDataBaseByVesion(string sqlText)
        {
            try
            {
                string sql = "SELECT TOP 1 [version] FROM yxs_version order by id";
                string version =ChangeHope.DataBase.SQLServerHelper.GetSingle(sql).ToString();
                int isNeedModify = sqlText.IndexOf("/*" + version + "*/");

                if (isNeedModify >= 0)
                {
                    sqlText = sqlText.Substring(isNeedModify);

                    string tmp = sqlText;
                    string separator = "/* YxShop SQL Separator */";
                    Hashtable ht = new Hashtable();
                    int i = 0;
                    int pos = tmp.IndexOf(separator);
                    while (pos != -1)
                    {
                        ht.Add(i, tmp.Substring(0, pos));
                        tmp = tmp.Substring(pos + separator.Length);
                        pos = tmp.IndexOf(separator);
                        i++;
                    }
                    ht.Add(i, tmp);
                    string[] array = new string[ht.Count];
                    for (int j = 0; j < ht.Count; j++)
                        array[j] = ht[j].ToString();

                    for (int f = 0; f < array.Length; f++)
                    {
                        ChangeHope.DataBase.SQLServerHelper.ExecuteSql(array[f]);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
